/*
 *  Copyright (c) 2015 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */package com.shengyuan.manage_os.im;

import java.io.File;

import java.io.InvalidClassException;

import android.app.AlarmManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.multidex.MultiDexApplication;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baidu.mapapi.SDKInitializer;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.shengyuan.manage_os.old.ying.boce.jsy.APIErpm;
import com.shengyuan.manage_os.old.ying.boce.jsy.MobileHandlerTask;
import com.shengyuan.manage_os.old.ying.erpm.BaseActivity;
import com.shengyuan.manage_os.old.ying.erpm.MainApplication;
import com.shengyuan.manage_os.old.ying.erpm.data.SharePreferenceUtil;
import com.shengyuan.manage_os.old.ying.erpm.util.CrashHandler;
import com.shengyuan.manage_os.im.common.utils.ToastUtil;
import com.shengyuan.manage_os.im.common.CCPAppManager;
import com.shengyuan.manage_os.im.common.utils.ECPreferenceSettings;
import com.shengyuan.manage_os.im.common.utils.ECPreferences;
import com.shengyuan.manage_os.im.common.utils.FileAccessor;
import com.shengyuan.manage_os.im.common.utils.LogUtil;
import com.shengyuan.manage_os.old.ying.erpm.util.SoundControler;
import com.shengyuan.manage_os.old.ying.erpm.util.Utility;

import oa.database.GreenDaoHelper;

/**
 * Created by Jorstin on 2015/3/17.
 */
public class ECApplication extends MainApplication {

    private static final String TAG = "ECApplication";
    private static ECApplication instance;

    public static Context Instance;
    public static BaseActivity currentActivity;
    public static APIErpm mApiErpm = new APIErpm();

    public static String AppRoot = Environment.getExternalStorageDirectory().getAbsolutePath()+"/jsy/";
    public static String cameraPath = AppRoot + "carmera_temp/";
    public static String voicePath = AppRoot + "voice_temp/";
    public static String filePath = AppRoot + "file_temp/";
    public static String UploadPath = AppRoot + "uploadfile/";
    public static String updatefile = AppRoot + "update.xml";
    public static String  MapRoot = "map";

    public static SharePreferenceUtil pShareUtil;
    public static MobileHandlerTask mobileHandlerTask ;
    public static AlarmManager mAlarmManager ;
    public static SoundControler mSoundControler ;

    public static Boolean APPDEBUG = false;

    /**
     * 单例，返回一个实例
     * @return
     */
    public static ECApplication getInstance() {
        if (instance == null) {
            LogUtil.w("[ECApplication] instance is null.");
        }
        return instance;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        GreenDaoHelper.initGreenDao(this);
        CCPAppManager.setContext(instance);
        FileAccessor.initFileAccess();
        setChattingContactId();
        initImageLoader();
		CrashHandler crashHandler = CrashHandler.getInstance();
		crashHandler.init(getApplicationContext());
        SDKInitializer.initialize(instance);
        requestQueue = Volley.newRequestQueue(this.getApplicationContext());


        Instance = this;
//        pShareUtil =  new SharePreferenceUtil(getApplicationContext());
//        mobileHandlerTask = new MobileHandlerTask();

    }

    @Override
    public void onTerminate() {
        super.onTerminate();
//        mobileHandlerTask.stop();
    }

    public static void CheckDirectory() {

        if (Utility.isExistExternalStore()) {
            AppRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + "/jsy/";
        }else{
            AppRoot = Instance.getFilesDir().getPath() + "/jsy/";
        }
        cameraPath = AppRoot + "camera_temp/";
        voicePath =  AppRoot + "voice_temp/";
        filePath = AppRoot + "file_temp/";
        MapRoot = AppRoot + "map_temp/";
        UploadPath = AppRoot + "uploadfiles/";
        MapRoot = AppRoot+"map/";
        File file = new File(AppRoot);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        file = new File(cameraPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        file = new File(voicePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        file = new File(filePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
        file = new File(UploadPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }

    }



    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }


    /**
     * 保存当前的聊天界面所对应的联系人、方便来消息屏蔽通知
     */
    private void setChattingContactId() {
        try {
            ECPreferences.savePreference(ECPreferenceSettings.SETTING_CHATTING_CONTACTID, "", true);
        } catch (InvalidClassException e) {
            e.printStackTrace();
        }
    }

    private void initImageLoader() {
        File cacheDir = StorageUtils.getOwnCacheDirectory(getApplicationContext(), "jsy/image");
        ImageLoaderConfiguration config = new ImageLoaderConfiguration
                .Builder(this)
                .threadPoolSize(1)//线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .memoryCache(new WeakMemoryCache())
                 .denyCacheImageMultipleSizesInMemory()
                .diskCacheFileNameGenerator(CCPAppManager.md5FileNameGenerator)
                        // 将保存的时候的URI名称用MD5 加密
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .diskCache(new UnlimitedDiscCache(cacheDir ,null ,CCPAppManager.md5FileNameGenerator))//自定义缓存路径
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                 .writeDebugLogs() // Remove for release app
                .build();//开始构建
        ImageLoader.getInstance().init(config);
    }

    /**
     * 返回配置文件的日志开关
     * @return
     */
    public boolean getLoggingSwitch() {
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(
                    getPackageName(), PackageManager.GET_META_DATA);
            boolean b = appInfo.metaData.getBoolean("LOGGING");
            LogUtil.w("[ECApplication - getLogging] logging is: " + b);
            return b;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return false;
    }

    public boolean getAlphaSwitch() {
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(
                    getPackageName(), PackageManager.GET_META_DATA);
            boolean b = appInfo.metaData.getBoolean("ALPHA");
            LogUtil.w("[ECApplication - getAlpha] Alpha is: " + b);
            return b;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return false;
    }
    public RequestQueue requestQueue;
    public RequestQueue getRequestQueue() {
        if (requestQueue == null) {
        }
        return this.requestQueue;
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }
}
